package com.plian.system.service.sys.per;

import com.plian.Tools.TokenUtil;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.dao.sys.fun.PerGroupDao;
import com.plian.system.dao.sys.per.PerUserDao;
import com.plian.system.dao.sys.per.PerUserOrgDao;
import com.plian.system.dao.sys.per.UserOrgDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 账号权限
 */
@Service
@Slf4j
public class PerUserService {
    @Autowired
    PerUserOrgDao perUserOrgDao;
    @Autowired
    UserOrgDao userOrgDao;
    @Autowired
    PerUserDao perUserDao;
    @Autowired
    PerGroupDao perGroupDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UserOrgService userOrgService;

    /**
     * 企业权限配置
     * @return
     */
    @Transactional(rollbackFor=RuntimeException.class)
    public ObjResult PerUserOrgConfig(PageData pd){
        try {
            saveUserOrg(pd);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }

    }

    public void saveUserOrg(PageData pd) throws Exception {
        String userId=pd.getString("userId");
        //前端传来旳集合
        List<HashMap<String,Object>> list= (List<HashMap<String, Object>>) pd.get("list");
        List<PageData> varList=new ArrayList<>();
        list.forEach(p -> {
            String userOrgId=p.get("userOrgId").toString();
            List<String> list_org= (List<String>) p.get("groupIds");
            if (list_org != null) {
                list_org.forEach(s->{
                    PageData p2=new PageData();
                    p2.put("id", UuidUtil.get32UUID());
                    p2.put("groupId",s);
                    p2.put("userOrgId",userOrgId);
                    varList.add(p2);
                });
            }
        });
        perUserOrgDao.del_PerUserOrg(userId);
        if(varList!=null &&varList.size()>0){
                perUserOrgDao.PerUserOrgConfig(varList);
        }
    }

    /**
     * 查询企业权限
     * @param pd
     * @return
     */
    public ObjResult PerUserOrgList(PageData pd){
        String userId=pd.getString("userId");
        ObjResult objResult;
        try {
            //当前用户下的单位权限
            List<PageData> l=userOrgDao.queryUserOrg(userId);
            //当前用户勾选权限时选择的单位
            List<PageData> l1=perUserOrgDao.queryPerUserOrg(userId);
//            //获取当前用户权限下的数组
            List<PageData> l2=perUserOrgDao.queryPerUserGroup(userId);
            //循环将有权限的标识
            l.forEach(pageData -> {
                pageData.put("check",false);
                List<PageData> l3=new ArrayList<>();
                l1.forEach(p ->{
                    if(pageData.getString("userOrgId").equals(p.getString("userOrgId"))){
                        pageData.put("check",true);
                    }
                });
                l2.forEach(p2->{
                    if(pageData.getString("userOrgId").equals(p2.getString("userOrgId"))){
                        l3.add(p2);
                    }
                });
                pageData.put("list",l3);
            });
            PageData p=new PageData();
            p.put("userId",userId);
            p.put("list",l);
            objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
      return objResult;
    }



    /**
     * 选择当前账号下，非企业操作员权限
     * @param pd
     * @return
     * @throws Exception
     */
    public ObjResult PerUserList(PageData pd)  {
        ObjResult objResult;
        String userId=pd.getString("userId");
        try {
            List<PageData> list= perUserDao.queryPerUser(userId);
            //不分页
            Page page=new Page(false,pd);
            List<PageData> listAll=perGroupDao.list(page);
            //循环将有权限的标识
            listAll.forEach(pageData -> {
                pageData.put("check",false);
                list.forEach(p ->{
                    if(pageData.getString("id").equals(p.getString("groupId"))){
                        pageData.put("check",true);
                    }
                });
            });
            PageData p=new PageData();
            p.put("userId",userId);
            p.put("list",listAll);
            objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    /**
     * 配置账号
     * @return
     */
    @Transactional(rollbackFor=RuntimeException.class)
    public ObjResult PerUserConfig(PageData pd){
        List<String> ids= (List<String>) pd.get("groupIds");
        String userId=pd.getString("userId");
        List<PageData> list=new ArrayList<>();
        ObjResult objResult;
        ids.forEach(s -> {
            PageData p=new PageData();
            p.put("userId",userId);
            p.put("id", UuidUtil.get32UUID());
            p.put("groupId",s);
            list.add(p);
        });
        try {
            perUserDao.del_PerUser(userId);
            if(list!=null &&list.size()>0){
                perUserDao.PerUserConfig(list);
            }
            objResult=new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }
    /*获取按钮*/
    public ListResult<PageData> getBtn(PageData pd){
        String userId= TokenUtil.getTokenUserId();
        ListResult listResult;
        try {
            PageData user= userDao.findbyid(userId);
            String url=pd.getString("url");
            List<PageData> list=new ArrayList<>();
            if("3".equals(user.getString("type"))){
                PageData p=new PageData();
                String orgId=TokenUtil.getTokenOrgId();
                p.put("userId",userId);
                p.put("orgId",orgId);
                p.put("url",url);
                list=perUserOrgDao.queryBtn(p);
            }else{
                PageData p=new PageData();
                p.put("userId",userId);
                p.put("url",url);
                list=perUserDao.queryBtn(p);
            }
            listResult=new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return listResult;
    }

    /**
     * 根据单位和角色id获取人员信息
     * @param pd
     * @return
     */
    public ListResult getUsers(PageData pd){
        try {
            List<PageData> list= perUserDao.getUsers(pd);
            ListResult listResult=new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

}
